package com.core.framework.web.easyweb.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.framework.web.easyweb.EasywebStatics;
import com.core.framework.web.easyweb.context.ServletActionContext;
import com.core.framework.web.easyweb.dispatcher.DispatcherAction;
/**
 * Easyweb Filter 处理初始化数据以及拦截页面信息并完成信息重组
 * @author 刘涛
 * @since Jun 11, 2012
 */
public class EasywebFilter implements EasywebStatics, Filter
{
	private ServletContext servletContext ;
	public void init(FilterConfig filterConfig) throws ServletException 
	{
		 servletContext = filterConfig.getServletContext();
	}

	public void doFilter(ServletRequest req, ServletResponse res,FilterChain filterChain) throws IOException, ServletException 
	{
		HttpServletRequest  request=(HttpServletRequest)req;
		HttpServletResponse response=(HttpServletResponse)res; 
		ServletActionContext.init(request,response,servletContext);
		DispatcherAction dispatcher = new DispatcherAction();
		String xrequest = request.getHeader("X-Requested-With");
		//是jquery ajax请求 
		if ( "XMLHttpRequest".equalsIgnoreCase(xrequest)) {
			try {
				dispatcher.excute();
				return;
			} catch (Exception e) {
				response.setHeader("msg", e.getMessage());
				response.sendError(700, e.getMessage());
				e.printStackTrace();
			}
			return;
		}
		else
		{
			try {
				dispatcher.excute();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			}
		}
		
	}
	public void destroy() {
		
	}


}
